/*!
 @header NoticeViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/25 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "NoticeViewController.h"
#import "Helper.h"
#import "Config.h"
#import "JMFBase.h"
#import "RTLabel.h"
#import <QuartzCore/QuartzCore.h>
#import "PersonalViewController.h"
#import "DynamicDetailViewController.h"
#import "OrderDetailViewController.h"
#import "ASImageView.h"
#import "IntegralRecordsDetailViewController.h"
#import "RelationConfirmationViewController.h"
#import "CircleHomeViewController.h"
#import "MJRefresh.h"

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：富文本的显示，一条消息通知中的文字可能存在不同的颜色。
//  	<实现描述>：RTLabel组件，为避免RTLabel显示文本的兼容性，所以不适用setText方法设置文本内容，
//                而采用RTLabelExtractedComponent。
//  	<注意事项>：1、在替换template的占位符时，应注意stringByReplacingOccurrencesOfString方法，返回的指针是指向不同地址，
//                 并且是autorelease的。
//                2、一定不能使用RTLabel的setText设置文本。
//
//  <功能描述>：下拉和加载更多
//  	<实现描述>：下拉：应重写并调用BaseRefreshViewController的reloadTableViewDataSource方法，在方法中实现自己的刷新数据源的方法。
//                加载更多：应重写并调用BaseRefreshViewController的refreshButtonEvent:方法，触发加载更多按钮事件。
//      <注意事项>：1、刷新时机，即_reloading，已经启动刷新时应将_reloading设为YES，防止刷新重复进行，刷新结束应将_reloading设为NO，准备下次刷新。
//                2、_isFooterRefresh，用于判断是否是加载更多，便于需要同时用到下拉和加载更多的地方判断如何刷新数据源。
//                《更多实现详见BaseRefreshViewController.m》
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface NoticeViewController ()<UIAlertViewDelegate,MJRefreshBaseViewDelegate>

@end

@implementation NoticeViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = _L(@"vc_title_032");
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundView = nil;
    
    //右按钮：清空所有记录
    UIButton* clearButton = [Helper buttonWithStyle:ButtonStyleNavigationClear];
    [clearButton addTarget:self action:@selector(clearButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clearButton];
    
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 832.0f/2.0f)];
    
    _dataSource = [NSMutableArray new];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 自定义事件

- (void)clearButtonEvent
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_127") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
    
    [alertView show];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if ( ! cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        ASImageView* thumbView = [[ASImageView alloc] initWithFrame:CGRectMake(8, 7, 30, 30)];
        [cell.contentView addSubview:thumbView];
        
        RTLabel* contentLabel = [[RTLabel alloc] initWithFrame:CGRectMake(45, 5, 230, 5)];
        contentLabel.font = _SYS_FONT_001;
        contentLabel.textColor = _SYS_COLOR_002;
        contentLabel.lineBreakMode = kCTLineBreakByWordWrapping;
        contentLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:contentLabel];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    NSDictionary *notice = [_dataSource objectAtIndex:indexPath.row];
    //通知类型
    NSInteger type = [[notice objectForKey:@"type"] integerValue];
    
    //去除无后续操作的row的DisclosureIndicator
    switch (type) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
        case 14:
        case 16:
        case 17:
        case 19:
        case 25:
        case 26:
        case 27:
        case 28:
        case 29:
        case 30:
        case 31:
        case 32:
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
            
        default:
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
            break;
    }
    //获得label应该显示的模板
    NSString *template = [notice objectForKey:@"template"];
    
    //设置头像
    NSURL* previewAvatarURL = [NSURL URLWithString:[notice objectForKey:@"userAvatarPreview"]];
    ASImageView* thumbView = [[cell.contentView subviews] objectAtIndex:0];
    [thumbView setImageURL:previewAvatarURL andSourceImageURL:nil forStyle:PictureStyleAvartPreview];
    
    //设置通知内容，替换template的“{}”样的占位符
    
    //    NSError *error = NULL;
    //    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\w+\\}" options:NSRegularExpressionCaseInsensitive error:&error];
    //    NSArray *matches = [regex matchesInString:template options:0 range:NSMakeRange(0, [template length])];
    //    for (NSTextCheckingResult *match in matches) {
    //        NSRange matchRange = [match range];
    //
    //        NSLog(@"%@",[template substringWithRange:matchRange]);
    //
    //
    //        //获得“{}”之间的内容
    //
    //        NSString *targetString = [template substringWithRange:matchRange];
    //        NSString *tempString = [targetString substringWithRange:NSMakeRange(1, [targetString length]-2)];
    //
    //
    //
    //    }
    //
    RTLabel* contentLabel = [[cell.contentView subviews] objectAtIndex:1];
    
    //此处不能直接用RTLabel的settext，否则会引起无html标记的文本不会正常换行
    RTLabelExtractedComponent *componentsDS = [RTLabel extractTextStyleFromText:[self replaceHolderInTemplate:template withNotice:notice] paragraphReplacement:@""];
    [contentLabel setText:@"" extractedTextComponent:componentsDS];

    CGSize optimzeSize = [contentLabel optimumSize];
    
    contentLabel.frame = CGRectMake(contentLabel.frame.origin.x, contentLabel.frame.origin.y, 230, optimzeSize.height);
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    NSDictionary *notice = [_dataSource objectAtIndex:indexPath.row];
    
    //通知类型
    NSInteger type = [[notice objectForKey:@"type"] integerValue];
    
    //对象类型
    NSInteger objectID = [[notice objectForKey:@"objectId"] integerValue];
    
    switch (type) {
            //评论了我的动态
        case 2:
            //推荐了我出售的商品动态
        case 3:
            //推荐了我推荐的商品动态
        case 4:
        case 29:
        {
            DynamicDetailViewController *trendDetailVC = [[DynamicDetailViewController alloc] initWithID:objectID];
            
            trendDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:trendDetailVC animated:YES];
        }
            break;
            //购买了我推荐的商品
        case 6:
        {
            IntegralRecordsDetailViewController *integralRecordsDetailVC = [[IntegralRecordsDetailViewController alloc] initWithStyle:UITableViewStylePlain ByRecordId:objectID];
            integralRecordsDetailVC.hidesBottomBarWhenPushed = YES;
            
            [self.navigationController pushViewController:integralRecordsDetailVC animated:YES];
        }
            break;
            
            //将我加入圈子
        case 1:
            //我注册成功后加入了TA邀请的圈子
        case 7:
        {
            PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:objectID];
            personalInfoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:personalInfoVC animated:YES];
        }
            break;
            
            //购买了我的商品
        case 5:
        case 8:
        case 9:
            
            //退款和退货
        case 14:
        case 16:
        case 17:
        case 19:
        case 25:
        case 26:
        case 27:
        case 28:
        {
            OrderDetailViewController *orderDetailViewController = [[OrderDetailViewController alloc] initWithOrderID:objectID];
            orderDetailViewController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:orderDetailViewController animated:YES];
        }
            break;
            
        case 10:
        case 11:
        case 12:
        {
            //开通了卖家服务
            UITabBarController *tabBarController = (UITabBarController *)self.view.window.rootViewController;
            tabBarController.selectedIndex = 3;
        }
            break;
        case 30:
        {
            RelationConfirmationViewController *relationConfirmationVC = [[RelationConfirmationViewController alloc] init];
            relationConfirmationVC.hidesBottomBarWhenPushed = YES;
            relationConfirmationVC.invitationId = objectID;
            [self.navigationController pushViewController:relationConfirmationVC animated:YES];
        }
            break;
        case 31:
        case 32:
        {
            NSInteger userId = [[notice objectForKey:@"userId"] integerValue];
            
            if (userId != 0) {
                
                PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:userId];
                personalInfoVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:personalInfoVC animated:YES];
            }
        }
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *notice = [_dataSource objectAtIndex:indexPath.row];
    NSString *template = [notice objectForKey:@"template"];

    CGSize size = [[self removeHTML:[self replaceHolderInTemplate:template withNotice:notice]] sizeWithFont:_SYS_FONT_001 constrainedToSize:CGSizeMake(230, 200) lineBreakMode:NSLineBreakByWordWrapping];
    
    if (size.height < 45) {
        return 45;
    }
    else {
        
        return size.height+10;
    }
}


#pragma mark - 私有方法

/*!
 @abstract 向服务器请求指定页数的消息通知
 @discussion 用于用户点击toolbar时，根据badgevalue请求消息通知
 @param pageSize 消息数
 */
- (void)noticesRequestWithPageSize:(NSInteger)pageSize
{
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_NOTICE_LIST];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    
    [request setValue:[NSString stringWithFormat:@"%d", pageSize] forParameter:@"pageSize"];
    [request asynchronous];
}

/*!
 @abstract 向服务器请求排在指定id后的消息通知
 @discussion 用于分页功能
 @param checkId 消息通知id，通常是数据源最后一条消息通知的ID
 */
- (void)noticesRequestWithCheckId:(NSInteger)checkId
{
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_NOTICE_LIST];
    request.delegate = self;
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:@(checkId) forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreNoticesDidReceived:)];
    }
    
    [request asynchronous];
}

///*!
// @abstract 实现下拉刷新
// @discussion 重写并调用父类的方法，，添加自定义的刷新方法
// */
//- (void)reloadTableViewDataSource{
//
//    [super reloadTableViewDataSource];
//
//    [self noticesRequestWithCheckId:nil];
//}
//
///*!
// @abstract 加载更多按钮事件
// @discussion 重写并调用父类的方法，添加自定义的刷新方法
// */
//- (void)refreshButtonEvent:(id)sender
//{
//    [super refreshButtonEvent:sender];
//
//    //如果原数据源为空，就没必要加载更多
//    if (_dataSource.count == 0) {
//
//        [Helper showAllTextDialog:_L(@"title_nomore_01") inView:self.view];
//
//        //设置成刷新模式为默认下拉刷新
//        _isFooterRefresh = NO;
//        self.disableBottomRefresh = YES;
//
//        return;
//    }
//
//    //获取此时数据源中最后一条记录的id
//
//    NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];
//
//    //发送加载更多的请求,数据接受成功后，设置_reloading
//    [self noticesRequestWithCheckId:checkId];
//}

/*!
 @abstract 获得数据源最后一条数据的ID
 @result 数据id
 */
- (NSInteger)catchTheLastDataSourceId
{
    if (_dataSource.count != 0) {
        
        return [[[_dataSource objectAtIndex:(_dataSource.count - 1)] objectForKey:@"id"] integerValue];
    }
    return 0;
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

//去掉文字中的HTML标签
- (NSString *)removeHTML:(NSString *)html{
    
    NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

    NSMutableArray *componentsToKeep = [NSMutableArray array];
    
    for (int i = 0; i < [components count]; i = i + 2) {
        
        [componentsToKeep addObject:[components objectAtIndex:i]];
        
    }

    NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
    
    return plainText;
    
}

- (NSString *)replaceHolderInTemplate:(NSString *)template withNotice:(NSDictionary *)notice
{
    if (template == nil || template.length == 0) {
        return nil;
    }
    if (notice == nil || notice.count == 0) {
        return nil;
    }
    
//    NSString *result;
    
    template = [template stringByReplacingOccurrencesOfString:@"{fromUser}" withString:[NSString stringWithFormat:@"<font color=red>%@</font>", [[notice objectForKey:@"params"] objectForKey:@"fromUser"]]];
    template = [template stringByReplacingOccurrencesOfString:@"{product}" withString:[NSString stringWithFormat:@"<font color='#86b60e'>%@</font>", [[notice objectForKey:@"params"] objectForKey:@"product"]]];
    template = [template stringByReplacingOccurrencesOfString:@"{points}" withString:[NSString stringWithFormat:@"<font color='#fc6f00'>%@</font>", [[notice objectForKey:@"params"] objectForKey:@"points"]]];
    template = [template stringByReplacingOccurrencesOfString:@"{content}" withString:[NSString stringWithFormat:@"%@", [[notice objectForKey:@"params"] objectForKey:@"content"]]];
    
    return template;
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
//    NSLog(@"%@",dict);
    if (jmf.status == JMStatusSucceed) {
        
        [self.navigationController.tabBarItem setBadgeValue:nil];
        
        if (_dataSource.count != 0) {
            [_dataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_dataSource.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }

    //数据源为空，显示友好的空页面
    if (_dataSource.count == 0) {
        
        if (_blankPage != nil && _blankPage.superview == nil) {
            _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_003@2x" ofType:@"png"]];
            self.view.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:_blankPage];
        }
        
    }else{
        self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
        [_blankPage removeFromSuperview];
    }
}

//加载更多
- (void)moreNoticesDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)noticesDidCleared:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:jmf.message inSeconds:1.5f];
        [_dataSource removeAllObjects];
        
        [self reloadTableView];
        
        //先判断空view是否已经被添加在视图上，避免重复添加
        if (_blankPage != nil && _blankPage.superview == nil) {
            _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_003@2x" ofType:@"png"]];
            self.view.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:_blankPage];
        }
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}
//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_NOTICE_CLEAR];
        request.delegate = self;
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        [request setSuccessSelector:@selector(noticesDidCleared:)];
        [request asynchronous];
    }
}


#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self noticesRequestWithCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
           [self noticesRequestWithCheckId:[self catchTheLastDataSourceId]];
        }
    }
}

- (void)dealloc
{
    _dataSource = nil;
}
@end
